package com.jctrip.hotel.source.xxl.elong.thread;

import com.google.common.collect.Lists;
import com.jctrip.hotel.common.constant.RedisKeyConstant;
import com.jctrip.hotel.common.context.BeanContext;
import com.jctrip.hotel.common.util.RedisUtil;
import com.jctrip.hotel.source.service.elong.ElongService;
import com.jctrip.hotel.source.service.elong.ElongTaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.time.DateUtils;

import java.util.Date;
import java.util.List;

/**
 * @Author: zxy
 * @CreateTime: 2023-11-17 11:01
 * @Description:
 */
@Slf4j
public class SyncElongOnlineRatesThread implements Runnable {
    private final String sourceId;
    private final String secretId;
    private final String secretKey;
    private final String user;
    private final String local;
    private final Integer days;

    public SyncElongOnlineRatesThread(String sourceId, String user, String secretId, String secretKey, String local, Integer days) {
        this.sourceId = sourceId;
        this.user = user;
        this.secretId = secretId;
        this.secretKey = secretKey;
        this.local = local;
        this.days = days;
    }

    @Override
    public void run() {
        try {
            RedisUtil redisUtil = BeanContext.getApplicationContext().getBean(RedisUtil.class);
            ElongTaskService elongTaskService = BeanContext.getApplicationContext().getBean(ElongTaskService.class);
            ElongService elongService = BeanContext.getApplicationContext().getBean(ElongService.class);
            List<String> hotels = Lists.newArrayList();
            String hotelCode;
            Date start = new Date();
            Date end = DateUtils.addDays(start, days);
            while (redisUtil.lGetListSize(RedisKeyConstant.SYNC_MAIN_ELONG_HOTEL_ONLINE_RATE_PUSH) > 0) {
                try {
                    String hotelId = (String) redisUtil.rightPop(RedisKeyConstant.SYNC_MAIN_ELONG_HOTEL_ONLINE_RATE_PUSH);
                    if (StringUtils.isBlank(hotelId)) {
                        continue;
                    }
                    hotels.add(elongService.parseHotelId(hotelId));
                    if (hotels.size() >= 10) {
                        hotelCode = String.join(",", hotels.subList(0, 10));
                        hotels.removeAll(hotels.subList(0, 10));
                        elongTaskService.syncHotelOnlineRates(sourceId, user, secretId, secretKey, local, hotelCode, start, end, days);
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
            if (hotels.size() > 0) {
                hotelCode = String.join(",", hotels);
                elongTaskService.syncHotelOnlineRates(sourceId, user, secretId, secretKey, local, hotelCode, start, end, days);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
